﻿//------------------------------------------------------------
// GenericPool
// Copyright © 2025 Mao Yin Hang. All rights reserved.
//------------------------------------------------------------
namespace GenericPool
{
    public class ObjectPool<T> : IBaseObjectPool
    {
        public ObjectPool(Action<T>? actionOnGet, Action<T> actionOnRelease)
        {
            this.m_ActionOnGet = actionOnGet;
            this.m_ActionOnRelease = actionOnRelease;
        }

        private readonly Stack<T> m_Stack = new Stack<T>();

        private readonly Action<T>? m_ActionOnGet;

        private readonly Action<T> m_ActionOnRelease;

        public int countAll
        {
            get;
            private set;
        }

        public int countActive
        {
            get
            {
                return countAll - countInactive;
            }
        }

        public int countInactive
        {
            get
            {
                return m_Stack.Count;
            }
        }

        public T Get()
        {
            T t;
            lock (typeof(T))
            {
                if (m_Stack.Count == 0)
                {
                    t = Activator.CreateInstance<T>();
                    countAll++;
                }
                else
                {
                    t = m_Stack.Pop();
                }
                if (m_ActionOnGet != null)
                {
                    m_ActionOnGet(t);
                }
            }

            return t;
        }

        public void Release(T element)
        {
            lock (typeof(T))
            {
                if (m_ActionOnRelease != null)
                {
                    m_ActionOnRelease(element);
                }
                m_Stack.Push(element);
            }
        }

        public void Clear()
        {
            m_Stack.Clear();
        }
    }

}
